package com.itogis.rest.controler;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.itogis.rest.po.ModifyPasswordPo;
import com.itogis.rest.po.SysMenuSet;
import com.itogis.rest.po.SysRightInfo;
import com.itogis.rest.po.SysUserInfo;
import com.itogis.rest.po.VoteOption;
import com.itogis.rest.po.VotePageScript;
import com.itogis.rest.po.VoteResultStat;
import com.itogis.rest.po.VoteEvent;
import com.itogis.util.MD5;

/**
 * 登录
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/login")
public class LoginControler extends CommomsControler {
	@RequestMapping("/getXml.cyh")
	public void getXml(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("tree");
		root.addAttribute("id", "0");

		SysUserInfo userForm = (SysUserInfo) request.getSession().getAttribute(
				"userInfoBean");
		String userId = "";
		HttpSession session = request.getSession(false);
		if (session == null || session.getAttribute("userInfoBean") == null) {
			userId = null;
			throw new Exception("请登录!");
		} else {
			userForm = (SysUserInfo) request.getSession().getAttribute(
					"userInfoBean");
			userId = userForm.getUserId();
		}
		if (userId == null) {
			userId = "3";
		}
		List<SysRightInfo> ls = this.loginService.getTreeMenu(userId);
		this.loginService.iniTreeMenuXml(root, ls);

		/*
		 * Element item = root.addElement("item"); item.addAttribute("id",
		 * "reporttypes"); item.addAttribute("text", "报表类型");
		 * item.addAttribute("im0", "dhtmlxtree_icon.gif");
		 * item.addAttribute("im1", "dhtmlxtree_icon.gif");
		 * item.addAttribute("im2", "dhtmlxtree_icon.gif"); Element sonItem =
		 * item.addElement("userdata"); sonItem.addAttribute("name",
		 * "desc").addText("演示所有报表"); sonItem = item.addElement("userdata");
		 * sonItem.addAttribute("name", "groupnode").addText("true");
		 * 
		 * 
		 * Element subItem = item.addElement("item"); subItem.addAttribute("id",
		 * "listpage"); subItem.addAttribute("text", "数据自动列表报表"); sonItem =
		 * subItem.addElement("userdata"); sonItem.addAttribute("name",
		 * "pageid").addText("listreportpage1"); sonItem =
		 * subItem.addElement("userdata"); sonItem.addAttribute("name",
		 * "configfilename").addText("report_reportypes.xml"); sonItem =
		 * subItem.addElement("userdata"); sonItem.addAttribute("name",
		 * "desc").addText("这里演示了对数据库数据进行自动列表显示的报表类型，并为这种报表类型演示了两种常见的应用场合，一个是显示普通数据列表，另一个是显示新闻列表"); //
		 * sonItem = subItem.addElement("userdata"); //
		 * sonItem.addAttribute("name", "groupnode").addText(null); // sonItem =
		 * subItem.addElement("userdata"); // sonItem.addAttribute("name",
		 * "otherfilename").addText(null); // sonItem =
		 * subItem.addElement("userdata"); // sonItem.addAttribute("name",
		 * "params").addText(null);
		 * 
		 * subItem = item.addElement("item"); subItem.addAttribute("id",
		 * "blocklist"); subItem.addAttribute("text", "块数据自动列表报表"); sonItem =
		 * subItem.addElement("userdata"); sonItem.addAttribute("name",
		 * "pageid").addText("blocklistpage1"); sonItem =
		 * subItem.addElement("userdata"); sonItem.addAttribute("name",
		 * "configfilename").addText("report_reportypes.xml"); sonItem =
		 * subItem.addElement("userdata"); sonItem.addAttribute("name",
		 * "desc").addText("999这里演示了对数据库数据进行自动列表显示的报表类型，并为这种报表类型演示了两种常见的应用场合，一个是显示普通数据列表，另一个是显示新闻列表"); //
		 * sonItem = subItem.addElement("userdata"); //
		 * sonItem.addAttribute("name", "groupnode").addText(null); // sonItem =
		 * subItem.addElement("userdata"); // sonItem.addAttribute("name",
		 * "otherfilename").addText(null); // sonItem =
		 * subItem.addElement("userdata"); // sonItem.addAttribute("name",
		 * "params").addText(null);
		 */
		String content = document.asXML();
		System.out.println(content);
		response.setContentType("text/xml; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter pw = response.getWriter();
		pw.write(content);
		pw.flush();
		pw.close();
	}

	/**
	 * 登录验证
	 * 
	 * @param request
	 * @param response
	 * @param userInfo:
	 *            form提交的用户登录信息，前端的name与form的属性对应
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/in.cyh")
	public String login(HttpServletRequest request,
			HttpServletResponse response, SysUserInfo userInfo)
			throws IOException {
		// response,request会自动传进来
		String message = "";
		int b = loginService.login(userInfo.getLoginId(), userInfo
				.getPassword());
		/** 登录成功,进入系统主界面 */
		request.setAttribute("loginName", "");
		System.out.println("checkNumLogin="+checkNumLogin);
		if("true".equals(checkNumLogin)){
			try {
				com.itogis.interceptors.randomNumImage.RandomNumberImageServlet
						.validateCheckNumber(request, userInfo
								.getCheckNumberInput());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (b == 2) {
			MD5 md5 = new MD5();
			userInfo.setPassword(md5.getMD5ofStr(userInfo.getPassword()));
			userInfo.setUserId(this.loginService.getUserId(userInfo
					.getLoginId()));
			userInfo.setUserName(this.loginService.getUserName(userInfo
					.getLoginId()));
			userInfo.setCode(this.loginService.getUserKfbm(userInfo
					.getLoginId()));
			userInfo.setDepartment(this.loginService.getUserdepartment(userInfo
					.getLoginId()));

			/** 获取权限菜单 */
			request.setAttribute("menu", this.loginService.getMenu(userInfo
					.getUserId()));
			request.setAttribute("function", this.loginService
					.getFunction(userInfo.getUserId()));

			SysMenuSet sysMenuSet = this.loginService.getMenuSet();
			request.setAttribute("menuSet", sysMenuSet);
			/** 保存log信息 */

			/** 保存用户session信息 */
			request.getSession().setAttribute("userInfoBean", userInfo);

			return sysMenuSet.getIndexPage();
		}

		/** 登录失败,返回登录页面 */
		else {
			if (b == -2) {
				message = "请输入账号和用户名!";
			} else if (b == 0) {
				message = "您输入的用户不存在!";
			} else {
				message = "您输入的密码不正确!";
				request.setAttribute("loginName", userInfo.getLoginId());
			}
			request.setAttribute("message", message);
			return "system/login.jsp";
		}

	}

	@RequestMapping("/logout.cyh")
	public String logout(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		request.getSession().setAttribute("userInfoBean", null);
		request.setAttribute("message", "");
		return "system/login.jsp";
	}

	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	@RequestMapping("/viewIndex.cyh")
	public String viewIndex(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		SysUserInfo userForm = (SysUserInfo) request.getSession().getAttribute(
				"userInfoBean");
		/** 获取权限菜单 */
		request.setAttribute("menu", this.loginService.getMenu(userForm
				.getUserId()));
		request.setAttribute("function", this.loginService.getFunction(userForm
				.getUserId()));

		SysMenuSet sysMenuSet = this.loginService.getMenuSet();
		request.setAttribute("menuSet", sysMenuSet);
		/** 保存log信息 */
		return "system/xxkindexView.jsp";
	}

	@RequestMapping("/toViewIndex.cyh")
	public void toViewIndex(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("/rest/login/viewIndex.cyh");
		RequestDispatcher requestDispatcher = request.getRequestDispatcher(sb
				.toString());
		requestDispatcher.forward(request, response);
	}

	@RequestMapping("/ipLogin.cyh")
	public String ipLogin(HttpServletRequest request,
			HttpServletResponse response, SysUserInfo userInfo)
			throws IOException {
		if (!ipLogin.equals("true")) {
			request.setAttribute("message", "系统不允许IP登录");
			return "system/login.jsp";
		}
		String ip = getIpAddr(request);

		String message = "";
		int b = loginService.ipLogin(ip);
		if (b == -2) {
			message = "IP非法或不在线!";
		} else if (b == 1) {
			message = "您IP地址还没有注册,请注册!";
		}
		/** 登录成功,进入系统主界面 */
		if (b == 0) {
			userInfo = this.loginService.getUserIdByIP(ip);
			// userInfo.setUserId(userInfo.getUserId());
			/** 获取权限菜单 */
			request.setAttribute("menu", this.loginService.getMenu(userInfo
					.getUserId()));
			request.setAttribute("function", this.loginService
					.getFunction(userInfo.getUserId()));

			SysMenuSet sysMenuSet = this.loginService.getMenuSet();
			request.setAttribute("menuSet", sysMenuSet);
			/** 保存log信息 */
			userInfo.setCode(this.loginService.getUserKfbm(userInfo
					.getLoginId()));
			/** 保存用户session信息 */
			request.getSession().setAttribute("userInfoBean", userInfo);

			return sysMenuSet.getIndexPage();
		}

		/** 登录失败,返回登录页面 */
		else {
			request.setAttribute("message", message);
			return "system/login.jsp";
		}

	}

	/**
	 * 初始化登录页面
	 * 
	 * @param request
	 * @param response
	 * @param userInfo
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/init")
	public String loginInit(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		return "system/login.jsp";
	}

	@RequestMapping("/gototAllVotePage.no")
	public String gototAllVotePage(@RequestParam("id")
	String id, HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) throws NumberFormatException, Exception {
		VotePageScript votePageScript = loginService.getVoteScriptPageById(Long
				.valueOf(id));
		if (votePageScript != null) {
			if (votePageScript.getType().equals("SCRIPT")) {
				modelMap.addAttribute("pageScriptCode", votePageScript
						.getScript());
			} else if (votePageScript.getType().equals("SQL")) {
				String[] sqlArray = votePageScript.getScript().split("~");
				String tableScript = "<style>	table {border-collapse:collapse;border:1px solid #EEE;font-size:14px;}	.row_head{background:#EEE;border-bottom:1px solid #CCC;padding:4px; font-size:16px;}	td{border:1px solid #DDD;padding:4px;}</style>";
				tableScript = tableScript
						+ "<div style=\"overflow:scroll;height:380px;width100px\">";

				for (int i = 0; i < sqlArray.length; i++) {
					tableScript = tableScript
							+ loginService.selectSQLToPrintTable(sqlArray[i]);
				}
				modelMap.addAttribute("pageScriptCode", tableScript);
				tableScript = tableScript + "</div>";
			}
			return votePageScript.getPageUrl();
		} else {
			return "system/login.jsp";
		}
	}

	@RequestMapping("/getVote.no")
	public void getVote(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) throws Exception {
		String eventId = "";
		if (request.getParameter("eventId") == null) {
			if (request.getAttribute("eventId") != null) {
				eventId = request.getAttribute("eventId").toString();
			}
		} else {
			eventId = request.getParameter("eventId");
		}
		// eventName = "CRM项目组11月度评优";
		VoteEvent event = loginService.getVoteEventById(Long.valueOf(eventId));
		if (event == null) {
			request.setAttribute("errMessage", "问卷名称不存在");
		}
		String userId = null;
		SysUserInfo userForm = (SysUserInfo) request.getSession().getAttribute(
				"userInfoBean");
		HttpSession session = request.getSession(false);
		if (session == null || session.getAttribute("userInfoBean") == null) {
			userId = null;
		} else {
			userForm = (SysUserInfo) request.getSession().getAttribute(
					"userInfoBean");
			userId = userForm.getUserId();
		}
		String clientIp = request.getRemoteAddr();
		List<VoteOption> list = loginService.getVoteOptionByEventId(event,
				userId, clientIp);
		request.setAttribute("viewpoint", list);
		request.setAttribute("event", event);
		StringBuilder sb = new StringBuilder();
		sb.append("/rest/login/toVote.no");
		RequestDispatcher requestDispatcher = request.getRequestDispatcher(sb
				.toString());
		requestDispatcher.forward(request, response);
	}

	@RequestMapping("/toVote.no")
	public String toVote(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) throws Exception {
		VoteEvent voteEvent = (VoteEvent) request.getAttribute("event");
		// return "system/void1.jsp";
		return voteEvent.getPageUrl();
	}

	@RequestMapping("/voteDo.no")
	public void vote(@RequestParam("eventId")
	String eventId, @RequestParam("viewpointId")
	String viewpointId, @RequestParam("viewpointMes")
	String viewpointMes, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap)
			throws ServletException, IOException, Exception {
		VoteEvent event = loginService.getVoteEventById(Long.valueOf(eventId));
		try {
			String userId = null;
			SysUserInfo userForm = (SysUserInfo) request.getSession()
					.getAttribute("userInfoBean");
			HttpSession session = request.getSession(false);
			if (session == null || session.getAttribute("userInfoBean") == null) {
				userId = null;
			} else {
				userForm = (SysUserInfo) request.getSession().getAttribute(
						"userInfoBean");
				userId = userForm.getUserId();
			}
			String clientIp = request.getRemoteAddr();
			String[] temp = viewpointId.split(",");
			String[] mes = viewpointMes.split("\\*");
			this.loginService.submitVote(Long.valueOf(eventId), temp, mes,
					clientIp, userId);
			request.setAttribute("checkIds", "");
			request.setAttribute("speakMess", "");
			request.setAttribute("message", "投票成功");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("message", e.getMessage());
			request.setAttribute("checkIds", viewpointId);
			request.setAttribute("speakMess", viewpointMes);
		}
		request.setAttribute("eventName", event.getName());

		this.getVote(request, response, modelMap);
	}

	@RequestMapping("/checkVoteResult.cyh")
	public String checkVoteResult(@RequestParam("eventId")
	String eventId, HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) throws NumberFormatException, Exception {
		VoteEvent event = loginService.getVoteEventById(Long.valueOf(eventId));
		List<VoteResultStat> list = this.loginService
				.getVoteResultStatOnLineByEventIds(String
						.valueOf(event.getId()));
		modelMap.addAttribute("voteList", list);
		modelMap.addAttribute("name", event.getName());
		modelMap.addAttribute("desc", event.getDescription());
		return "system/voteResult.jsp";
	}

	/**
	 * 修改密码初始化
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/modifyPasswordInit.cyh")
	public String modifyPasswordInit(HttpServletRequest request,
			HttpServletResponse response) {
		if (null == request.getSession().getAttribute("userInfoBean")) {
			request.setAttribute("message", "请登录后访问");
			return "system/login.jsp";
		}
		SysUserInfo userForm = (SysUserInfo) request.getSession().getAttribute(
				"userInfoBean");
		String loginid = userForm.getLoginId();
		request.setAttribute("loginid", loginid);
		return "system/modifypassword.jsp";
	}

	@RequestMapping("/initWeekWork.cyh")
	public String initWeekWork(HttpServletRequest request,
			HttpServletResponse response) {
		if (null == request.getSession().getAttribute("userInfoBean")) {
			request.setAttribute("message", "请登录后访问");
			return "system/login.jsp";
		}
		String groupId = "";
		if (request.getParameter("groupId") == null) {
			if (request.getAttribute("groupId") != null) {
				groupId = request.getAttribute("groupId").toString();
			}
		} else {
			groupId = request.getParameter("groupId");
		}
		if (groupId == null || "".equals(groupId)) {

		}
		SysUserInfo userForm = (SysUserInfo) request.getSession().getAttribute(
				"userInfoBean");
		String loginid = userForm.getLoginId();
		request.setAttribute("loginid", loginid);
		request.setAttribute("groupId", groupId);
		request.setAttribute("workMes", loginService.getWeekWorkByUseId(Long
				.valueOf(userForm.getUserId()), groupId));

		return "system/weekWorkManage.jsp";
	}

	@RequestMapping("/submitWeekWork.cyh")
	public String submitWeekWork(HttpServletRequest request,
			HttpServletResponse response, ModifyPasswordPo modifyPasswordPo) {
		if (null == request.getSession().getAttribute("userInfoBean")) {
			request.setAttribute("message", "请登录后访问");
			return "system/login.jsp";
		}
		String groupId = "";
		if (request.getParameter("groupId") == null) {
			if (request.getAttribute("groupId") != null) {
				groupId = request.getAttribute("groupId").toString();
			}
		} else {
			groupId = request.getParameter("groupId");
		}
		if (groupId == null || "".equals(groupId)) {

		}
		SysUserInfo userForm = (SysUserInfo) request.getSession().getAttribute(
				"userInfoBean");
		String userid = userForm.getUserId();

		String message = "";

		if (loginService.updateWeekWork(userid, modifyPasswordPo.getPassword(),
				groupId)) {
			message = "修改成功!";
		} else {
			message = "修改失败!请与管理员联系";
		}
		request.setAttribute("workMes", loginService.getWeekWorkByUseId(Long
				.valueOf(userForm.getUserId()), groupId));
		request.setAttribute("message", message);
		request.setAttribute("groupId", groupId);
		request.setAttribute("loginid", userForm.getLoginId());
		return "system/weekWorkManage.jsp";
	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/modifyPassword.cyh")
	public String modifyPassword(HttpServletRequest request,
			HttpServletResponse response, ModifyPasswordPo modifyPasswordPo) {
		if (null == request.getSession().getAttribute("userInfoBean")) {
			request.setAttribute("message", "请登录后访问");
			return "system/login.jsp";
		}
		SysUserInfo userForm = (SysUserInfo) request.getSession().getAttribute(
				"userInfoBean");
		String userid = userForm.getUserId();
		MD5 md5 = new MD5();
		String password = md5.getMD5ofStr(modifyPasswordPo.getPassword());
		String md5newPassword = md5.getMD5ofStr(modifyPasswordPo
				.getNewpassword());
		String oldPassword = userForm.getPassword();
		String message = "";
		if ("loginPass".equals(modifyPasswordPo.getModifyType())) {
			if (!modifyPasswordPo.getNewpassword().equals(
					modifyPasswordPo.getConfirmpassword())) {
				message = "输入两次新密码不一致!";
			} else {
				if (password.equals(oldPassword)) {
					if (loginService.updatePassword(userid, md5newPassword)) {
						message = "修改成功!";
					} else {
						message = "修改失败!请与管理员联系";
					}

				} else {
					request.setAttribute("newPassword", modifyPasswordPo
							.getNewpassword());
					message = "原密码不正确!";
				}
			}
		} else if ("loginIp".equals(modifyPasswordPo.getModifyType())
				|| "unLoginIp".equals(modifyPasswordPo.getModifyType())) {
			if (password.equals(oldPassword)) {
				String ip = getIpAddr(request);
				if ("unLoginIp".equals(modifyPasswordPo.getModifyType())) {
					ip = "";
				}
				SysUserInfo sysUserInfo = loginService.getUserIdByIP(ip);
				if (sysUserInfo.getUserId() == null) {
					if (loginService.updateLoginIP(userid, ip)) {
						message = "修改成功!";
					} else {
						message = "修改失败!请与管理员联系";
					}
				} else {
					if (!userForm.getUserId().equals(sysUserInfo.getUserId())) {
						message = "您当前注册的IP地址已被其它人注册.";
					} else {
						message = "修改成功.";
					}
				}
			} else {
				request.setAttribute("newPassword", modifyPasswordPo
						.getNewpassword());
				message = "原密码不正确!";
			}
		}

		request.setAttribute("message", message);
		request.setAttribute("loginid", userForm.getLoginId());
		return "system/modifypassword.jsp";
	}
}
